package com.northwest_man.refactor_tool;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 1. 先遍历java文件中的R.string.\S+
 * 2. 再到res/values/strings.xml文件中知道key那一行
 * 3. 复制到目标module中的res/values/strings.xml文件
 */
public class CopyStringInJava {
    private static final boolean debug = true;
    private static final String module_name = "module_check_in";
    private static final String javaFileDir = "/Users/yong.hu/AndroidStudioProjects/patpat/" + module_name + "/src/main/java";


    private static final String from_module_root_dir = "/Users/yong.hu/AndroidStudioProjects/patpat/Patpat";
    private static final String to_module_root_dir = "/Users/yong.hu/AndroidStudioProjects/patpat/" + module_name;
    private static final String resource_dir = "/src/main/res";

    private static final String from_module_resource_dir = from_module_root_dir + resource_dir;
    private static final String to_module_resource_dir = to_module_root_dir + resource_dir;

    private enum ResourceType {
        // <string\s+name\s*=\s*"
        // "\s*>[\S\s]+?</\s*string\s*>
        string("R\\.string\\.([a-zA-Z0-9_]+)",
                "strings.xml",
                "values[\\S]*",
                "<string\\s+name\\s*=\\s*\"",
                "\"\\s*>[\\S\\s]+?</\\s*string\\s*>",
                "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources>",
                "</resources>", "<resources\\s*>"),
        /*ids("R\\.id\\.([a-zA-Z0-9_]+)",
                "ids.xml",
                "values[\\S]*",
                "xml",
                "",
                string.fileHeader,
                string.fileFooter,
                string.fileHeaderRegex)*/;

        public final String javaRegex;
        public final String resourceFileName;
        public final String resourceDirRegex;
        public final String keyPreRegex;
        public final String keySufRegex;
        public final String fileHeader;
        public final String fileFooter;
        public final String fileHeaderRegex;


        ResourceType(final String javaRegex,
                     final String resourceFileName,
                     final String resourceDirRegex,
                     final String keyPreRegex,
                     final String keySufRegex,
                     final String fileHeader,
                     final String fileFooter,
                     final String fileHeaderRegex) {
            this.javaRegex = javaRegex;
            this.resourceFileName = resourceFileName;
            this.resourceDirRegex = resourceDirRegex;
            this.keyPreRegex = keyPreRegex;
            this.keySufRegex = keySufRegex;
            this.fileHeader = fileHeader;
            this.fileFooter = fileFooter;
            this.fileHeaderRegex = fileHeaderRegex;
        }

        // 把各个文件夹的strings.xml找到
        public List<String> getFromFileList() {
            final File file = new File(from_module_resource_dir);
            final List<String> resultFileList = new ArrayList<>();
            if (file.isDirectory()) {
                final File[] allFile = file.listFiles();
                if (allFile == null) return resultFileList;
                for (final File item : allFile) {
                    if (item.isFile()) continue;
                    if (item.getName().matches(this.resourceDirRegex)) {
                        final File[] secondaryFileList = item.listFiles();
                        if (secondaryFileList == null) continue;
                        for (final File secondaryFile : secondaryFileList) {
                            if (secondaryFile.getName().equals(this.resourceFileName)) {
                                resultFileList.add(secondaryFile.getAbsolutePath());
                            }
                        }
                    }
                }
            }
            return resultFileList;
        }

        // 生成to目录下不存在的目录
        public List<String> generateToFolder(final List<String> fromFileList) {
            final List<String> toFileList = new ArrayList<>();
            if (fromFileList == null) return toFileList;
            for (final String item : fromFileList) {
                final int startIndex = item.lastIndexOf(resource_dir);
                final String toFilePath = to_module_root_dir + item.substring(startIndex);
                toFileList.add(toFilePath);
                final File file = new File(toFilePath);
                final File parentFolder = file.getParentFile();
                final boolean createFolderSuccess;
                if (!parentFolder.exists()) {
                    createFolderSuccess = parentFolder.mkdirs();
                } else createFolderSuccess = true;
                if (createFolderSuccess) {
                    if (file.exists()) {

                        final StringBuffer fileContent;
                        try {
                            fileContent = new StringBuffer(FileUtils.readFileToString(file));
                            final Pattern pattern = Pattern.compile(this.fileHeaderRegex);
                            final Matcher matcher = pattern.matcher(fileContent);
                            if (!matcher.find()) {

                                FileUtils.writeStringToFile(file, this.fileHeader, false);
                                FileUtils.writeStringToFile(file, this.fileFooter, true);
                            }

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        try {
                            final boolean success = file.createNewFile();
                            if (success) {


                                FileUtils.writeStringToFile(file, this.fileHeader, false);
                                FileUtils.writeStringToFile(file, this.fileFooter, true);

                            } else {
                                System.out.println("创建失败：" + toFilePath);

                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                } else {
                    throw new RuntimeException(parentFolder.getAbsolutePath() + " 文件夹创建失败");
                }
            }
            if (toFileList.size() != fromFileList.size()) {
                throw new RuntimeException();
            }

            return toFileList;
        }


        public String getKeyRegex(final String key) {
            return this.keyPreRegex + key + this.keySufRegex;
        }


    }

    public static void cp() {
        cp(javaFileDir);
    }

    private static void cp(final String javaFileDir) {
        final File javaFile = new File(javaFileDir);
        if (javaFile.isDirectory()) {
            final File[] allFile = javaFile.listFiles();
            if (allFile == null) return;
            for (final File item : allFile) {
                cp(item.getAbsolutePath());
            }

        } else {
            cp2(javaFile);
        }
    }

    private static void cp2(final File javaFile) {
        final StringBuilder javaFileContent = FileUtil.getFileContent(javaFile.getAbsolutePath());
        if (javaFileContent == null) return;
        final StringBuilder stringBuilder = new StringBuilder();
        final ResourceType[] allResourceType = ResourceType.values();
        final Map<ResourceType, StringBuffer> test__ResourceIdMap = new HashMap<>();
        for (final ResourceType item : allResourceType) {
            final Pattern pattern = Pattern.compile(item.javaRegex);
            final Matcher matcher = pattern.matcher(javaFileContent);
            final StringBuffer test__allResourceId = new StringBuffer();
            while (matcher.find()) {
                final String resourceKey = matcher.group(1);
                test__allResourceId.append(matcher.group()).append("\n");
                final List<String> resFromFileList = item.getFromFileList();
                final List<String> resToFileList = item.generateToFolder(resFromFileList);
                if (debug) {
                    System.out.println("------------------------------------------------------");
                    for (final String test__fromResourceFile : resFromFileList) {
                        System.out.println(test__fromResourceFile);
                    }
                    System.out.println("\n");
                    for (final String test__fromResourceFile : resToFileList) {
                        System.out.println(test__fromResourceFile);
                    }
                    System.out.println("------------------------------------------------------");
                }
                if (false) continue;
                for (int i = resFromFileList.size() - 1; i >= 0; i--) {
                    final String resFromFilePath = resFromFileList.get(i);
                    final String resToFilePath = resToFileList.get(i);
                    final StringBuilder copy = new StringBuilder();

                    final StringBuilder resFromFileContent = FileUtil.getFileContent(resFromFilePath);
                    if (resFromFileContent == null) continue;
                    final Pattern resFromFilePattern = Pattern.compile(item.getKeyRegex(resourceKey));
                    final Matcher resFromFileMatcher = resFromFilePattern.matcher(resFromFileContent);

                    while (resFromFileMatcher.find()) {
                        final String matchRow = resFromFileMatcher.group();
                        copy.append(matchRow).append("\n");

                    }


                    final StringBuilder resToFileContent = FileUtil.getFileContent(resToFilePath);
                    if (resToFileContent == null) {
                        System.out.printf("这个to文件居然为空：%20s\n", resToFilePath);
                    } else {
                        final Pattern resToFilePattern = Pattern.compile(item.fileHeaderRegex);
                        final Matcher resToFileMatcher = resToFilePattern.matcher(resToFileContent);
                        if (resToFileMatcher.find()) {
                            resToFileContent.insert(resToFileMatcher.end(), copy);
                            try {
                                FileUtils.writeStringToFile(new File(resToFilePath), resToFileContent.toString());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        } else {
                            System.out.println("------------------------------------------------------");
                            System.out.println(resToFileContent);
                            System.out.println("------------------------------------------------------");

                        }
                    }


                }

            }
            test__ResourceIdMap.put(item, test__allResourceId);
        }
        if (debug) {
            System.out.println("------------------------------------------------------");
            for (final Map.Entry<ResourceType, StringBuffer> test__entry : test__ResourceIdMap.entrySet()) {

                System.out.println("******************************************************");
                System.out.println(test__entry.getKey());
                System.out.println(test__entry.getValue());

            }
            System.out.println("------------------------------------------------------");

        }
        if (stringBuilder.length() > 0) {

            System.out.println("以下文件复制失败：");
            System.out.println(stringBuilder);
        }
    }


}
